package com.hl.domain;

import com.hl.mapper.CouponMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class Scheduling {
    @Autowired
    private CouponMapper couponMapper;
//定时任务，每隔五秒执行一次
//@Scheduled(cron = "*/5 * * * * ?")
    private void scheduling() {
//    System.out.println("执行定时任务");
    //查询数据库中状态为未开始的优惠券
    List<Coupon> coupons = couponMapper.selectCouponstatus();
    //查询数据库中状态为进行中的优惠券
    List<Coupon> coupons1 = couponMapper.selectCouponstatus1();
    if (coupons.size()>0){
        for (Coupon coupon : coupons) {
            Date startTime = coupon.getStartTime();
            //将Date类型转换为LocalDateTime类型

            LocalDateTime startDateTime = startTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

            LocalDateTime now = LocalDateTime.now();
            if (now.isAfter(startDateTime)) {
                coupon.setStatus("ACTIVE");
                System.out.println("更新优惠卷"+coupon.getId()+"状态为ACTIVE");
                couponMapper.updateCoupon(coupon);
            }
        }
    }
  if (coupons1.size()>0){
      for (Coupon coupon : coupons1) {
          Date endTime = coupon.getEndTime();
          //将Date类型转换为LocalDateTime类型
          LocalDateTime endDateTime = endTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
          LocalDateTime now = LocalDateTime.now();
          if (now.isAfter(endDateTime)) {
              coupon.setStatus("EXPIRED");
              System.out.println("更新优惠卷"+coupon.getId()+"状态为EXPIRED");
              couponMapper.updateCoupon(coupon);
          }
      }
  }


}
}
